<template>
  <div class="container">
    <div class="content">
      <div class="top-row">
        <span class="title">营业时间设置</span>
        <el-button class="el-dropdown-link" type="primary" plain :icon="Plus" @click="saveComponentState.callout()">添加 </el-button>
      </div>
      <el-table :data="rules" style="width: 100%" stripe>
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="type" label="规则类型" width="120">
          <template #default="{ row }">
            <el-tag :type="BusinessRuleType.ORDINARY === row.type ? 'success' : 'danger'">{{ businessRuleTypeLabelOf(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="作用时间" width="280">
          <template #default="{ row }">
            <template v-if="BusinessRuleType.ORDINARY === row.type">
              <el-tag effect="plain" v-for="(week, index) in (row.weeks ?? '').split(',')" :key="index">{{ getWeekLabel(parseInt(week)) }}</el-tag>
            </template>
            <template v-else>
              <p :style="{ color: isExpired(row.endDate) ? '#909399' : '#5cacfd' }">
                <el-tag effect="plain">
                  <span>{{ row.startDate }}~{{ row.endDate }} </span>
                  <span v-if="isExpired(row.endDate)">（已过期）</span>
                </el-tag>
              </p>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="时间段">
          <template #default="{ row }">{{ row.times }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template v-slot="scope">
            <el-button :link="true" size="small" :icon="Edit" @click="editHandle(scope.row.id)">修改</el-button>
            <el-button :link="true" size="small" :icon="Delete" @click="deleteHandle(scope.row.id)" class="delBut">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <SaveDialog
        title="经营时间规则"
        v-model:visible="saveComponentState.visible"
        :id="saveComponentState.form.id"
        @query="saveComponentState.query()"
        @save="(callback) => saveComponentState.save(callback)"
        @cancel="saveComponentState.cancel()"
        width="55%"
      >
        <template #body>
          <el-form ref="classData" :model="saveComponentState.form" :rules="saveComponentState.rules" label-width="auto">
            <el-form-item label="类型：" prop="name">
              <el-radio-group v-model="saveComponentState.form.type">
                <el-radio :value="1" size="default" checked>{{ businessRuleTypeLabelOf(BusinessRuleType.ORDINARY) }}（周）</el-radio>
                <el-radio :value="2" size="default">{{ businessRuleTypeLabelOf(BusinessRuleType.SPECIAL) }}（时间段）</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="生效时间：" prop="name" v-show="saveComponentState.form.type">
              <el-checkbox-group
                v-model="saveComponentState.form._weeks"
                size="small"
                v-if="saveComponentState.form.type === BusinessRuleType.ORDINARY"
              >
                <el-checkbox label="周一" :value="1" border />
                <el-checkbox label="周二" :value="2" border />
                <el-checkbox label="周三" :value="3" border />
                <el-checkbox label="周四" :value="4" border />
                <el-checkbox label="周五" :value="5" border />
                <el-checkbox label="周六" :value="6" border />
                <el-checkbox label="周日" :value="7" border />
              </el-checkbox-group>
              <el-date-picker
                v-model="saveComponentState.form._timeRanges"
                range-separator="~"
                type="daterange"
                value-format="YYYY-MM-DD"
                v-if="saveComponentState.form.type === BusinessRuleType.SPECIAL"
              />
            </el-form-item>
            <el-form-item label="经营的时间段：" prop="name" v-show="saveComponentState.form.type">
              <time-ranges
                :time-ranges="saveComponentState.form.times"
                @change="(timeRangesArr) => (saveComponentState.form.times = timeRangesArr.join(','))"
              />
            </el-form-item>
          </el-form>
        </template>
      </SaveDialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { BusinessRuleType, businessRuleTypeLabelOf } from '@/enums/BusinessRuleType'
import ComponentHat from '@/plugins/type'
import ShopBusinessRules from '@/types/entity/ShopBusinessRules'
import { TimeOperations } from '@/utils/TimeUtils'
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import SaveDialog from '@/components/save-dialog/index.vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import TimeRanges from '@/components/time-ranges/index.vue'
const { $API, $modal } = <ComponentHat>getCurrentInstance().proxy
const rules = ref<ShopBusinessRules[]>([])
async function refreshList() {
  const result = await $API.businessTime.queryShopBusinessTimeRules()
  if (!result.success) {
    $modal.alertError(result.message)
    return
  }
  rules.value = result.data
}

onMounted(() => {
  refreshList()
})
// 当点击编辑规则时
const editHandle = (ruleId: number) => {
  saveComponentState.form.id = ruleId
  saveComponentState.visible = true
}
// 点击菜品的删除按钮时
const deleteHandle = async (ruleId: number) => {
  const result = await $API.businessTime.remove(ruleId)
  if (result.success) {
    $modal.msgSuccess('删除规则成功！')
    // 刷新当前页数据
    refreshList()
  } else {
    $modal.msgError('删除规则失败！' + result.message)
  }
}
function getWeekLabel(dayNumber: number): string {
  const weekDays: { [key: number]: string } = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    7: '周日'
  }
  return weekDays[dayNumber]
}
function isExpired(date: string): boolean {
  return Date.now() > new TimeOperations().init(date).getTimestamp()
}

// save or insert components dialog state
const saveComponentState = reactive({
  rules: {
    // name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
    // sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  },
  visible: false,
  form: new ShopBusinessRules(),
  async query() {
    const result = await $API.businessTime.queryShopRuleById(saveComponentState.form.id)
    if (!result.success) {
      $modal.msgError(result.message)
      return false
    }
    Object.assign(saveComponentState.form, result.data)
    // 兼容回显
    saveComponentState.form._weeks = saveComponentState.form.weeks.split(',').map(Number)
    saveComponentState.form._timeRanges = [saveComponentState.form.startDate, saveComponentState.form.endDate]
    return true
  },
  async save(callback: (success: boolean) => void) {
    // 将表单数据转为后端需要的
    if (this.form._weeks != null) this.form.weeks = this.form._weeks.join(',')
    if (this.form._timeRanges != null) {
      this.form.startDate = this.form._timeRanges[0]
      this.form.endDate = this.form._timeRanges[1]
    }
    // 保存
    const result = await (this.form.id == null ? $API.businessTime.add(this.form) : $API.businessTime.update(this.form))
    callback(result.success)
    // 将form置空
    if (result.success) {
      refreshList()
      this.form = new ShopBusinessRules()
    }
  },
  cancel() {
    // 将form置空
    this.form = new ShopBusinessRules()
  },
  callout() {
    saveComponentState.visible = true
  }
})
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;

  .content {
    display: flex;
    overflow: auto;
    padding: 20px;
    width: 100%;
    height: 100%;
    background-color: #fff;
    flex-direction: column;
    box-sizing: border-box;

    .top-row {
      display: flex;
      justify-content: space-between;
      align-items: self-start;

      .title {
        padding: 0 0 20px;
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
}
</style>
